import settings from "../utils/settings";
import renderBeaconBeam2 from "../../BeaconBeam";
import { timedisplay , getskulltextures, getItemFromGui, drawBoxAtEntity, DrawString, Auctions, GetAttributesFrom, sendEssentialNotifications, RemoveEmoji, getPlayerPos, getEntityHP, getItemSBID, MessageID, Angle, ServerTick } from "../utils/utils";
import { location } from "../utils/getLocation";
import { guiMover } from "../utils/gui";
import { Vec3 } from "../utils/vec3";

let kuudralocation = {
    player: "p1&p2",
    kuudra: null,
    hp : 0,
    p4 : false,
    getKuudra() {
        if(this.kuudra && this.kuudra.isDead()) this.kuudra = null;
        if(!this.kuudra && location.inKuudra) {
            World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityMagmaCube).filter(e => e.getWidth().toFixed(0) == 15 && getEntityHP(e).maxhp == 100000).forEach(e => {
                if(!this.kuudra) this.kuudra = e;
            })
        }

        if (this.kuudra) this.hp = getEntityHP(this.kuudra).hp;
        else {
            const wither = World.getAllEntitiesOfType(net.minecraft.entity.boss.EntityWither).filter(e => e.getName().removeFormatting().includes("﴾ Kuudra ﴿"))[0];
            if(wither) this.hp = getEntityHP(wither).hp / 300 * 100000; else this.hp = 0;
        }
    },
    checkplayerlocation() {
        let x = Player.getRenderX();
        let y = Player.getRenderY();
        let z = Player.getRenderZ();
        if(x > -200 && y > 64 && z > -200 && x < -14 && y < 173 && z < -17) this.player = "p1&p2";
        if(x > -186 && y > 14 && z > -197 && x < -130 && y < 63 && z < -134) this.player = "p3";
        if(x > -133 && y > 0 && z > -137 && x < -74 && y < 63 && z < -76) this.player = "p4";
    }
}


//如果在kuudra内每秒看看目前在哪块地图
register("step", () => {
    if(location.inKuudra) kuudralocation.checkplayerlocation();
}).setDelay(1)

//找kuudra
register("tick", () => { 
    if(location.inKuudra) kuudralocation.getKuudra();
})
register("worldLoad", () => {
    kuudralocation.kuudra = null;
    kuudralocation.p4 = false;
})

//显示kuudra血量
register("renderOverlay", () => {
    if(settings.ShowKuudraHP != 1) return;
    if(guiMover.gui.isOpen()){
        let hptext = "99988";
        hptext = hptext.slice(0,hptext.length - 3) + ',' + hptext.slice(hptext.length - 3);
        DrawString("§4§l" + hptext + "/100,000" , guiMover.settings.KuudraHP.x - hptext.length * 4 * guiMover.settings.KuudraHP.s , guiMover.settings.KuudraHP.y , guiMover.settings.KuudraHP.s , true);
        return;
    }
    if(!location.inKuudra || kuudralocation.hp < 2) return;
    if (location.location == "Kuudra's Hollow (T5)" && kuudralocation.hp < 25000 && kuudralocation.player == "p4") {
        let hptext = parseInt(kuudralocation.hp/25000*240).toString() + 'M'
        DrawString("§4§l" + hptext + "/240M" , guiMover.settings.KuudraHP.x - hptext.length * 4 * guiMover.settings.KuudraHP.s , guiMover.settings.KuudraHP.y , guiMover.settings.KuudraHP.s , true);
    } else {
        let hptext = parseInt(kuudralocation.hp).toString();
        if(kuudralocation.hp >= 1000) hptext = hptext.slice(0,hptext.length - 3) + ',' + hptext.slice(hptext.length - 3);
        DrawString("§4§l" + hptext + "/100,000" , guiMover.settings.KuudraHP.x - hptext.length * 4 * guiMover.settings.KuudraHP.s , guiMover.settings.KuudraHP.y , guiMover.settings.KuudraHP.s , true);
    }
})

register("renderWorld", () => {
    if(settings.ShowKuudraHP != 2 || !location.inKuudra || kuudralocation.hp < 2) return;
    const wither = World.getAllEntitiesOfType(net.minecraft.entity.boss.EntityWither).filter(e => e.getName().removeFormatting().includes("﴾ Kuudra ﴿"))[0];
    if(!wither) return;
    if (location.location == "Kuudra's Hollow (T5)" && kuudralocation.hp < 25000 && kuudralocation.player == "p4") 
        wither.getEntity().func_96094_a("§6﴾ §c§lKuudra§6 ﴿ §4§l" + (parseInt(kuudralocation.hp/2500*240)/10).toString() + "M§c❤");  //setCustomNameTag
    else {
        let hptext = parseInt(kuudralocation.hp).toString();
        if(kuudralocation.hp >= 1000) hptext = hptext.slice(0,hptext.length - 3) + ',' + hptext.slice(hptext.length - 3);
        let submerge = "";
        Scoreboard.getLines().filter(e => RemoveEmoji(e.getName().removeFormatting()).startsWith("Submerges In:")).forEach(e => {submerge = "   §r" + RemoveEmoji(e.getName()).replace(" In","")});
        wither.getEntity().func_96094_a("§6﴾ §c§lKuudra§6 ﴿ " + (kuudralocation.hp > 60000 ? "§a" : (kuudralocation.hp > 40000 ? "§e" : "§4")) + "§l" + hptext + "§c❤" + submerge);  //setCustomNameTag
    }
})

//box kuudra
register("renderWorld", (ticks) => {
    if(kuudralocation.kuudra && settings.ShowWhereKuudra && settings.ShowWhereKuudra != 2 && kuudralocation.hp > 1) drawBoxAtEntity(kuudralocation.kuudra,1,0,0,1,15,15,15,ticks,5,true);
})

const magmaImage = Image.fromAsset("MagmaCube.png");
register("renderOverlay", () => {
    if(settings.ShowWhereKuudra < 2 || !kuudralocation.kuudra || kuudralocation.hp < 2) return;
    let yaw = 0;
    if(kuudralocation.player == "p4") {
        const angle = Angle.getAngleWithPos(kuudralocation.kuudra.getX() + 7.5,kuudralocation.kuudra.getY(),kuudralocation.kuudra.getZ() + 7.5);
        yaw = Player.getYaw() - angle.yaw;
    } else {
        if(kuudralocation.p4) {
            switch (true) {
                case (kuudralocation.kuudra.getZ() > -92): yaw = 0; break;
                case (kuudralocation.kuudra.getX() < -114): yaw = 270; break;
                case (kuudralocation.kuudra.getZ() < -118): yaw = 180; break;
                case (kuudralocation.kuudra.getX() > -89): yaw = 90; break;
                default: return;
            }
        } else return;
    }
    const radian = (yaw * Math.PI) / 180;
    const Scale = Renderer.screen.getScale();
    const x = Renderer.screen.getWidth() / 2 - (40 / Scale) * Math.sin(radian);
    const y = Renderer.screen.getHeight() / 2 - (40 / Scale) * Math.cos(radian);
    Renderer.drawImage(magmaImage, x - 12 / Scale , y - 12 / Scale , 24 / Scale , 24 / Scale);
})

//phase time
let phaseTime = {
    start : 0,
    p1 : 0,
    p2 : 0,
    p3 : 0,
    p4 : 0
};
register("worldLoad", () => { for (let p in phaseTime) { phaseTime[p] = 0; } });
register("chat", (message) => {
    if(!settings.kuudraPhaseTime || !location.inKuudra) return;
    try {
        switch (message) {
            case "Okay adventurers, I will go and fish up Kuudra!":
                phaseTime.start = ServerTick.getTime();
                break;
            case "Uh oh.":
            case "Not again!":
                if(settings.kuudrawelcometitle) Client.showTitle("&c&lKuudra &r&c已苏醒","&r&r&e[NPC] &cElle&f: &rNope, that's just a Magmafish!",10,50,20);
                break;
            case "OMG! Great work collecting my supplies!":
                phaseTime.p1 = ServerTick.getTime() - phaseTime.start;
                ChatLib.chat("§6§l[BZA] §cKuudra PHASE 1 - SUPPLIES  用时: " + timedisplay(phaseTime.p1));
                break;
            case "Phew! The Ballista is finally ready! It should be strong enough to tank Kuudra's blows now!":
                phaseTime.p2 = ServerTick.getTime() - phaseTime.start - phaseTime.p1;
                ChatLib.chat("§6§l[BZA] §cKuudra PHASE 2 - BUILDING THE BALLISTA  用时: " + timedisplay(phaseTime.p2));
                break;
            case "POW! SURELY THAT'S IT! I don't think he has any more in him!":
                phaseTime.p3 = ServerTick.getTime() - phaseTime.start - phaseTime.p1 - phaseTime.p2;
                if(location.location == "Kuudra's Hollow (T5)") chat("§6§l[BZA] §cKuudra PHASE 3 - STUNNING KUUDRA  用时: " + timedisplay(phaseTime.p3));
                break;
            case "Good job everyone. A hard fought battle come to an end. Let's get out of here before we run into any more trouble!":
                phaseTime.p4 = ServerTick.getTime() - phaseTime.start - phaseTime.p1 - phaseTime.p2 - phaseTime.p3;
                ChatLib.chat("§6§l[BZA] §cKuudra PHASE 1 - SUPPLIES  用时: " + timedisplay(phaseTime.p1));
                ChatLib.chat("§6§l[BZA] §cKuudra PHASE 2 - BUILDING THE BALLISTA  用时: " + timedisplay(phaseTime.p2));
                if(location.location == "Kuudra's Hollow (T5)") {
                    ChatLib.chat("§6§l[BZA] §cKuudra PHASE 3 - STUNNING KUUDRA  用时: " + timedisplay(phaseTime.p3));
                    ChatLib.chat("§6§l[BZA] §cKuudra PHASE 4 - TRUE LAIR  用时: " + timedisplay(phaseTime.p4));
                } else {
                    ChatLib.chat("§6§l[BZA] §cKuudra PHASE 3" + ((location.location == "Kuudra's Hollow (T3)" || location.location == "Kuudra's Hollow (T4)") ? " - STUNNING KUUDRA" : " - FUEL") + "  用时: " + timedisplay(phaseTime.p3 + phaseTime.p4));
                }
                break;
        }
    } catch (error) {
        console.error(JSON.stringify(error,undefined,true));
    }
}).setCriteria("[NPC] Elle: ${message}")

//dropship
let Dropship = -1;
register("tick", () => {
    if(settings.Dropship && location.inKuudra && kuudralocation.player != "p4") {
        Dropship = -1;
        World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityGhast).filter(a => a.distanceTo(-100.6 , 99 , -107.3) < 30).forEach( e => {
        if (e.distanceTo(-100.6 , 99 , -107.3) < Dropship || Dropship == -1){
            Dropship = parseInt(e.distanceTo(-100.6 , 99 , -107.3));
        }
    })
    }
})

//[NPC] Elle: A group of Wandering Blazes are emerging from Kuudra's mouth!
let boxBlaze = 0;
register("chat",(message)=>{
    if(settings.WanderingBlazes && location.inKuudra && message.includes("Wandering Blazes") && Scoreboard.getLineByIndex(2).toString().includes("Protect Elle")){
        Client.showTitle("§4§lWandering Blazes","",0,40,0);
        World.playSound("mob.blaze.breathe",1,1);
        boxBlaze = Date.now() + 15000;
    }
}).setCriteria("[NPC] Elle: ${message}!")
register("worldLoad",() => {boxBlaze = 0;})

register("renderWorld",(tick) => {
    if(settings.WanderingBlazes && location.inKuudra && boxBlaze > Date.now()) World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityBlaze).forEach(e => {drawBoxAtEntity(e,0.91,0.7,0.09,1,1,1,2,tick,2,true)});
})

//fuel
let fuel = -1;
register("tick",()=>{
    if(!settings.Fuel || !location.inKuudra || fuel == 0 || fuel == 25) return;
    World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName() == "§fEnergy Charge: §a0%").forEach((e)=>{
        fuel = 0;
    });
})
register("chat",(player,num)=>{
    if(!settings.Fuel) return;
    if(!location.inKuudra) return;
    fuel = num;
    if(settings.Fueltitle) Client.showTitle("§fEnergy Charge: §a" + num + "%","",0,30,10);
}).setChatCriteria("${player} recovered a Fuel Cell and charged the Ballista! (${num}%)")

//kuudra stun timer
let kuudrastuntime = 0;
let kuudradown = 0;
let kuudrap4 = 0;

register("renderOverlay", () => {
    if(guiMover.gui.isOpen()) {
        if(settings.Fuel) DrawString("§fEnergy Charge: §a50%" , guiMover.settings.EnergyCharge.x , guiMover.settings.EnergyCharge.y , guiMover.settings.EnergyCharge.s , true);
        if(settings.Dropship) DrawString("§4§lDropship 18" , guiMover.settings.Dropship.x , guiMover.settings.Dropship.y , guiMover.settings.Dropship.s , true);
        if(settings.stun) DrawString("§aKuudra is stunned , §4§l" + timedisplay(8888) + " §aleft" , guiMover.settings.KuudraStun.x , guiMover.settings.KuudraStun.y , guiMover.settings.KuudraStun.s , true);
    } else {
        if(fuel >= 0 && kuudralocation.player != "p4") DrawString("§fEnergy Charge: §a" + fuel + "%" , guiMover.settings.EnergyCharge.x , guiMover.settings.EnergyCharge.y , guiMover.settings.EnergyCharge.s , true);
        if(settings.Dropship && Dropship > -1 && kuudralocation.player != "p4") DrawString("§4§lDropship " + (Dropship ? Dropship : "Now!") , guiMover.settings.Dropship.x , guiMover.settings.Dropship.y , guiMover.settings.Dropship.s , true);
        if(settings.stun) {
            if(kuudrastuntime > ServerTick.getTime()) {
                DrawString("§aKuudra is stunned , §4§l" + timedisplay(kuudrastuntime - ServerTick.getTime()) + " §aleft" , guiMover.settings.KuudraStun.x , guiMover.settings.KuudraStun.y , guiMover.settings.KuudraStun.s , true);
            }else if(kuudradown > ServerTick.getTime()){
                DrawString("§4§lKuudra down! " + timedisplay(kuudradown - ServerTick.getTime()) , guiMover.settings.KuudraStun.x , guiMover.settings.KuudraStun.y , guiMover.settings.KuudraStun.s , true);
            }else if(kuudrap4 > ServerTick.getTime()){
                DrawString("§4§lPHASE 4 - TRUE LAIR" , guiMover.settings.KuudraStun.x , guiMover.settings.KuudraStun.y , guiMover.settings.KuudraStun.s , true);
            }
        }
    }
})
register("chat",(player)=>{
    if(!location.inKuudra) return;
    if(kuudrastuntime < ServerTick.getTime()){
        if(location.location.includes("T5")){
            kuudrastuntime = ServerTick.getTime() + 8000;
        }else if(location.location.includes("T3")){
            kuudrastuntime = ServerTick.getTime() + 12000;
        }else{
            kuudrastuntime = ServerTick.getTime() + 10000;
        }
    };
}).setChatCriteria("${player} destroyed one of Kuudra's pods!")

register("chat",()=>{
    if(!location.inKuudra) return;
    kuudrastuntime = 0;
    fuel = -1;
    kuudralocation.p4 = true;
    if(location.location.includes("T5")){
        kuudrap4 = ServerTick.getTime() + 3000;
        Dropship = -1;
        World.playSound("note.pling", 1, 2.0);
        setTimeout(() => { World.playSound("note.pling", 1, 2.0); }, 333);
        setTimeout(() => { World.playSound("note.pling", 1, 2.0); }, 666);
        setTimeout(() => { World.playSound("note.pling", 1, 2.0); }, 999);
        setTimeout(() => { World.playSound("note.pling", 1, 2.0); }, 1332);
    }else{
        kuudradown = ServerTick.getTime() + 15300;
    }
}).setChatCriteria("[NPC] Elle: POW! SURELY THAT'S IT! I don't think he has any more in him!")

//KuudraWaypoints
let KuudraWaypoints = [];
let stun = ["","","",""];

register("tick", () => {
    if(!settings.KuudraWaypoints || !location.inSkyblock) return;
    KuudraWaypoints = [];
    stun[0]="";stun[1]="";stun[2]="";stun[3]="";
    if(!location.inKuudra || Scoreboard.getLines()[2] == undefined) return;
    switch (RemoveEmoji(Scoreboard.getLineByIndex(2).toString()).removeFormatting().replace(/ \(.+\)/,"")) {
        case "Rescue supplies":
            World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(supplyies => supplyies.getName() == "§e§lBRING SUPPLY CHEST HERE").forEach(s => {
                KuudraWaypoints.push({x:s.getRenderX()-0.5,y:s.getRenderY(),z:s.getRenderZ()-0.5,str:"distance"});
            });
            World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityGiantZombie).filter(e => getskulltextures(e.getEntity().func_71124_b(0)) === "ewogICJ0aW1lc3RhbXAiIDogMTU5NDAyOTYxNjQyNCwKICAicHJvZmlsZUlkIiA6ICJkZGVkNTZlMWVmOGI0MGZlOGFkMTYyOTIwZjdhZWNkYSIsCiAgInByb2ZpbGVOYW1lIiA6ICJEaXNjb3JkQXBwIiwKICAic2lnbmF0dXJlUmVxdWlyZWQiIDogdHJ1ZSwKICAidGV4dHVyZXMiIDogewogICAgIlNLSU4iIDogewogICAgICAidXJsIiA6ICJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzI0YmJmZDlkODRmNDI0NTZjZDAyYTRiYWE1Y2QwNTRiY2VkMGRkYjJkMWM4MzIxYzgzZTVkNjY3Y2Q4NTU3NWEiCiAgICB9CiAgfQp9").forEach(s => {
                KuudraWaypoints.push({x:s.getRenderX()-2.5,y:s.getRenderY()+9.5,z:s.getRenderZ()+3.0,str:"distance"});
            });
            break;
        case "Protect Elle":
            World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(supply => supply.getName().startsWith("§7§lPROGRESS: ") && !supply.getName().endsWith("§a§lCOMPLETE")).forEach(s => {
                KuudraWaypoints.push({x:s.getRenderX()-0.5,y:s.getRenderY()+0.8,z:s.getRenderZ()-0.5,str:s.getName().split(' ').pop()});
            });
            break;
        default:
            if(settings.stuntoggle && kuudralocation.player == "p3"){ //kuudra stun 进度
                World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName().includes("Pod Condition") && e.distanceTo(-154 , 21 , -154) < 2).forEach((e)=>{
                    stun[0] = e.getName().replace("Pod Condition: ","");
                });
                World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName().includes("Pod Condition") && e.distanceTo(-151 , 21 , -171) < 2).forEach((e)=>{
                    stun[1] = e.getName().replace("Pod Condition: ","");
                });
                World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName().includes("Pod Condition") && e.distanceTo(-167 , 21 , -166) < 2).forEach((e)=>{
                    stun[2] = e.getName().replace("Pod Condition: ","");
                });
                World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName().includes("Lava rises") && e.distanceTo(-157 , 21 , -163) < 2).forEach((e)=>{
                    stun[3] = e.getName();
                    let sec = (kuudrastuntime > ServerTick.getTime() ? Math.floor((kuudrastuntime - ServerTick.getTime()) / 1000) + "" : e.getName().replace(/[^0-9]/ig,""));
                    if(Math.floor(sec) < 4 && Math.floor(sec) > 0) Client.showTitle("§4§l" + sec,"§cLava rises in",0,5,5);
                });
            }else{
                World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityGiantZombie).filter(e => getskulltextures(e.getEntity().func_71124_b(0)) === "ewogICJ0aW1lc3RhbXAiIDogMTcyMDAyOTIzMDk5OSwKICAicHJvZmlsZUlkIiA6ICJkM2Y5MjEyMjY3YzM0YzEwYWNjOWZkNGI5MDFkYjI0ZiIsCiAgInByb2ZpbGVOYW1lIiA6ICJkYXl3ZSIsCiAgInNpZ25hdHVyZVJlcXVpcmVkIiA6IHRydWUsCiAgInRleHR1cmVzIiA6IHsKICAgICJTS0lOIiA6IHsKICAgICAgInVybCIgOiAiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS9mZDcyZGViMWFiMDAzM2I0MmIwYTEyZWZjZjQ4M2YwZmJhMjZkYzUxZGVkMzkxOWViYWRiNzBmOTY1N2ExZjYxIgogICAgfQogIH0KfQ==").forEach(s => {
                    KuudraWaypoints.push({x:s.getRenderX()-2.5,y:s.getRenderY()+9.5,z:s.getRenderZ()+3.0,str:"distance"});
                });
            }
            break;
    }
})

register("renderWorld", () => {
    if(!location.inKuudra || !settings.KuudraWaypoints) return;
    if(KuudraWaypoints.length != 0) KuudraWaypoints.forEach(e => {
        renderBeaconBeam2(e.x,e.y,e.z,(settings.kuudraWaypointsColor.getRed()/255),(settings.kuudraWaypointsColor.getGreen()/255),(settings.kuudraWaypointsColor.getBlue()/255),(settings.kuudraWaypointsColor.getAlpha()/255),true);
        if(e.str) Tessellator.drawString((e.str === "distance" ? ("§e(§6" + Math.floor(getPlayerPos().distance(new Vec3(e.x,e.y,e.z))) + "m§e)") : e.str),e.x+0.5,e.y+1,e.z+0.5,0,true,0.05,false);
    })
    World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityEndermite).filter(e => !e.isDead()).forEach(e => {
        renderBeaconBeam2(e.x,e.y,e.z,1,0,0,0.7,true);
    })
})

register("worldLoad", () => {
    fuel = -1;
    Dropship = -1;
    if(KuudraWaypoints.length != 0) KuudraWaypoints.splice(0,KuudraWaypoints.length);
})

register("renderOverlay", () => {
    if(!settings.stuntoggle) return;
    if(guiMover.gui.isOpen()) {
        DrawString("      §4DESTROYED\n  §e40%  §a100%\n§fLava rises in: §a15s" , guiMover.settings.InKuudraStun.x , guiMover.settings.InKuudraStun.y , guiMover.settings.InKuudraStun.s , true);
        return;
    }
    if(stun[0] != "" || stun[1] != "" || stun[2] != "")
        DrawString("      " + stun[0] + "\n  " + stun[1] + "  " + stun[2] + "\n" + stun[3] , guiMover.settings.InKuudraStun.x , guiMover.settings.InKuudraStun.y , guiMover.settings.InKuudraStun.s , true);
})

//Perk Shop blacklist
register("guiMouseClick", (mx,my,button,gui,event) => {
    if(!settings.PerkShopB || !location.inKuudra) return;
    try {
        if(ChatLib.removeFormatting(Player.getContainer().getName()) != "Perk Menu") return;
        let item = getItemFromGui(gui);
        if(!item) return;
        let itemname = ChatLib.removeFormatting(item.getName());
        if(settings.PerkShopBL.split(",").indexOf(itemname) != -1) {
            cancel(event);
        };
    } catch (error) {
        return;
    }
})

//自动补充末影珍珠
register("chat", () => {
    if(!(location.inKuudra || location.inDungeon) || !settings.RefillEnderPearl || settings.RefillEnderPearl == 2) return;
    let EnderPearls = 0;
    Player.getInventory().getItems().filter(e => e && getItemSBID(e) === "ENDER_PEARL").forEach(e => {
        EnderPearls += e.getStackSize();
    });
    if(EnderPearls >= 16) return;
    ChatLib.command("getfromsacks ender pearl " + (16 - EnderPearls));
}).setCriteria(/(\[NPC\] Elle: Okay adventurers, I will go and fish up Kuudra!|Starting in 1 second.)/)

const autoRefillEnderPearl = register("playerInteract", () => {
    if(!location.inSkyblock || settings.RefillEnderPearl < 2) return;
    let heldItem = Player.getHeldItem();
    if(!heldItem || getItemSBID(heldItem) != "ENDER_PEARL" || heldItem.getStackSize() >= 4) return;
    ChatLib.command("getfromsacks ender pearl " + (16 - heldItem.getStackSize()));
    autoRefillEnderPearl.unregister();
    setTimeout(() => {
        autoRefillEnderPearl.register();
        setTimeout(() => {
            if(Player.getInventory().getItems().filter(e => e && getItemSBID(e) == "ENDER_PEARL").length == 0) ChatLib.command("getfromsacks ender pearl 16");
        }, 500);
    }, 1500);
})


/**
 * 返回Hypixel所在的美国西部时区的当前时间. 按照3月第二个周日凌晨3点前和11月第一个周日凌晨2点后算作冬令时(EST)进行计算
 * @returns {Date} 当前美国西部时间
 */
function GetHypixelTimeDate() {
    let localDateNow = new Date();
    let EDTTimeNow = new Date(localDateNow.getTime() + (localDateNow.getTimezoneOffset() - 4 * 60) * 60 * 1000);
    let secondSundayOfMar = 7 * 2 - (new Date(EDTTimeNow.getFullYear(), 2, 1).getDay() == 0 ? 7 : new Date(EDTTimeNow.getFullYear(), 2, 1).getDay()) + 1;
    let firstSundayInNov = 7 - (new Date(EDTTimeNow.getFullYear(), 10, 1).getDay() == 0 ? 7 : new Date(EDTTimeNow.getFullYear(), 10, 1).getDay()) + 1;
    let HypixelTimeNow = (
        //判断是否为冬令时
        (3 < EDTTimeNow.getMonth() + 1 && EDTTimeNow.getMonth() + 1 < 11) ||
        (EDTTimeNow.getMonth() + 1 == 3 && (EDTTimeNow.getDate() < secondSundayOfMar || (EDTTimeNow.getDate() == secondSundayOfMar && EDTTimeNow.getHours() <= 3))) ||
        (EDTTimeNow.getMonth() + 1 == 11 && (EDTTimeNow.getDate() > firstSundayInNov || (EDTTimeNow.getDate() == secondSundayOfMar && EDTTimeNow.getHours() >= 2)))
        ? new Date(EDTTimeNow.getTime() - 60 * 60 * 1000) : EDTTimeNow
        );
    return HypixelTimeNow;
}

/**
 * 获取 今天是今年第几天 . 默认按照美国西部时区计算.
 * @param {Date} date 输入的Date格式时间
 * @returns {Number} 返回的 今天是今年第几天
 */
function GetDayOfYear(date=GetHypixelTimeDate()) {
    return Math.floor((date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / (1000 * 60 * 60 * 24));
}

/**
 * Kuudra Follower 帽子价格查询
 * @param {string} name 要查询的玩家名,默认是自己
 * @returns {Number} 当前日期该玩家的帽子价格
 */
function GetKuudraFollowerHelmetPrice(name=Player.getName()) {
    //The total -------- plus time times time, all that subtracted from thrice the commencement, then add -- of yourself, the whole thing elbuod.
    //Wiki相关页面: hypixel wiki: https://wiki.hypixel.net/Kuudra_Follower_Armor   fandom wiki(带计算器): https://hypixel-skyblock.fandom.com/wiki/Kuudra_Follower_Armor
    return 13331996 + 2 * Math.pow(GetDayOfYear(), 2) - 58 * name.length;
}

/**
 * Kuudra Follower 帽子价格查询
 * @param {string} name 要查询的玩家名,默认是自己
 */
export function GetAndShowKuudraFollowerHelmetPrice(name=Player.getName()) {
    let hypTime = GetHypixelTimeDate();
    new Message(
        "§6§l[BZA] §a用户名§7: §b" + name + " §7,§a" + (name==Player.getName() ? "您" : "") + "今天的 §cKuudra Follower §a帽子价格为§7: §b" + GetKuudraFollowerHelmetPrice(name) + "   §e以下为计算所用的数据,建议检查以免出错" +
        "\n§e名称长度§7:§b" + name.length + " §7,§eDay of Year§7: §b" + GetDayOfYear() + " §7,§e日期和时间(ET)§7: §b" + hypTime.getFullYear() + "-" + (hypTime.getMonth() + 1) + "-" + hypTime.getDate() + " §b" + hypTime.getHours() + ":" + hypTime.getMinutes()
    ).chat();
}

register("chat", () => {
    if(!location.inSkyblock || location.island != "Crimson Isle") return;
    if(World.getAllEntitiesOfType(net.minecraft.entity.passive.EntitySquid).filter(e => e.distanceTo(Player.getPlayer()) < 20).length == 0) return;
    GetAndShowKuudraFollowerHelmetPrice(Player.getName());
}).setCriteria("[NPC] Kuudra Believer: Maybe Kuudra will show favor upon you.")


//末地石剑效果提示
register("chat" , (Mana) => {
    if(!settings.ExtremeFocus || !location.inKuudra || kuudralocation.player != "p4") return;
    let effectedPlayers = "";
    
    World.getAllPlayers().filter(e => e.getName() != Player.getName() && e.distanceTo(Player.getPlayer()) <= 5).forEach(e => {
        effectedPlayers += e.getName() + " ";
    });

    if(effectedPlayers) ChatLib.command("pc " + "Used Extreme Focus! ("+ Mana + " Mana) || For " + effectedPlayers);

}).setCriteria("Used Extreme Focus! (${Mana} Mana)")


//词条价格查询
const ItemsName = {
    attribute_shard:["ATTRIBUTE_SHARD"],
    helmet:["AURORA_HELMET","CRIMSON_HELMET","TERROR_HELMET","FERVOR_HELMET","HOLLOW_HELMET"],
    chestplate:["AURORA_CHESTPLATE","CRIMSON_CHESTPLATE","TERROR_CHESTPLATE","FERVOR_CHESTPLATE","HOLLOW_CHESTPLATE"],
    leggings:["AURORA_LEGGINGS","CRIMSON_LEGGINGS","TERROR_LEGGINGS","FERVOR_LEGGINGS","HOLLOW_LEGGINGS"],
    boots:["AURORA_BOOTS","CRIMSON_BOOTS","TERROR_BOOTS","FERVOR_BOOTS","HOLLOW_BOOTS"],
    molten_necklace:["MOLTEN_NECKLACE"],
    magma_necklace:["MAGMA_NECKLACE"],
    lava_shell_necklace:["LAVA_SHELL_NECKLACE"],
    thunderbolt_necklace:["THUNDERBOLT_NECKLACE"],
    molten_cloak:["MOLTEN_CLOAK"],
    ghast_cloak:["GHAST_CLOAK"],
    molten_belt:["MOLTEN_BELT"],
    blaze_belt:["BLAZE_BELT"],
    implosion_belt:["IMPLOSION_BELT"],
    molten_bracelet:["MOLTEN_BRACELET"],
    glowstone_gauntlet:["GLOWSTONE_GAUNTLET"],
    flaming_fist:["FLAMING_FIST"],
    gauntlet_of_contagion:["GAUNTLET_OF_CONTAGION"],
    magma_rod:["MAGMA_ROD"],
    inferno_rod:["INFERNO_ROD"],
    hellfire_rod:["HELLFIRE_ROD"],
}
function replaceAttributeName(attName) {
    return attName.replace(/_/g,' ').replace('mending','vitality');
}
function GetAttributesPrice(a1,a2) {
    if(!Auctions.lastUpdated) return null;
    let items = {};
    if(parseInt(a2) && parseInt(a2) < 11) {
        let item = Auctions.ItemWithAtt.filter(e => e.att[a1] == a2);
        items.shard = item.filter(e => e.id == "ATTRIBUTE_SHARD").splice(0,settings.ShowAttributesPrice);
        for (let key in ItemsName) {
            items[key] = item.filter(e => ItemsName[key].indexOf(e.id) != -1).splice(0,settings.ShowAttributesPrice);
        }
    } else {
        let item =  Auctions.ItemWithAtt.filter(e => e.att.hasOwnProperty(a1) && e.att.hasOwnProperty(a2));
        for (let key in ItemsName) {
            items[key] = [];
            ItemsName[key].forEach(e => {
                if(item.filter(a => a.id == e)[0]) items[key].push(item.filter(a => a.id == e)[0]);
            })
        }
    }
    return items;
}

function GetAttributesPriceFromItem(item) {
    if( !Auctions.lastUpdated || !GetAttributesFrom(item)) return null;
    let id = item.getNBT().getCompoundTag("tag").getCompoundTag("ExtraAttributes").getString("id");
    let type = '';
    for (let key in ItemsName) {
        if(ItemsName[key].indexOf(id) != -1) type = key;
    }
    if(!type) return null;
    let text = new Message();
    let att = GetAttributesFrom(item);
    let atts = [];
    for (let key in att) {
        atts.push(key);
        let lv = att[key];
        let i = GetAttributesPrice(key,lv)[type][0];
        if(i) text.addTextComponent(new TextComponent('§b' + replaceAttributeName(key) + ' ' + lv + ' §6在§b' + type.replace(/_/g,' ') + '§6上的价格是 §a' + (parseInt(i.price / 10000) / 100) + 'M').setHover("show_text",i.name + "\n" + i.lore).setClick("run_command","/viewauction " + i.ahid));
        else text.addTextComponent(new TextComponent('§b' + replaceAttributeName(key) + ' ' + lv + ' §6的§b' + type.replace(/_/g,' ') + '§6在市场上§c没有找到'));
        text.addTextComponent("\n");
    }
    if(atts.length == 2) {
        let i = GetAttributesPrice(atts[0],atts[1])[type].filter(n=>n.id == id)[0];
        if(i) text.addTextComponent(new TextComponent('§b' + replaceAttributeName(atts[0]) + ' §6和§b ' + replaceAttributeName(atts[1]) + ' §6在§b' + id.replace(/_/g,' ') + '§6上的价格是 §a' + (parseInt(i.price / 10000) / 100) + 'M').setHover("show_text",i.name + "\n" + i.lore).setClick("run_command","/viewauction " + i.ahid));
        else text.addTextComponent(new TextComponent('§b' + replaceAttributeName(atts[0]) + ' §6和§b ' + replaceAttributeName(atts[1]) + ' §6的§b' + id.replace(/_/g,' ') + '§6在市场上§c没有找到'));
        text.addTextComponent("\n");
    }
    return text;
}

//Kuudra奖励箱
let AttributesPriceText = [];
register("guiOpened" , () => {
    if(!settings.AttributesPrice || !location.inSkyblock || !location.inKuudra || !Auctions.lastUpdated) return;
    try { setTimeout(() => {
        if(Player.getContainer() == undefined || Player.getContainer().getName().removeFormatting() != "Paid Chest") return;
        let item = [Player.getContainer().getStackInSlot(11),Player.getContainer().getStackInSlot(12)].filter(e => e != null && GetAttributesFrom(e));
        if(item.length == 0 || Auctions.ItemWithAtt.length == 0) return;
        AttributesPriceText = [];
        item.forEach(e => {
            AttributesPriceText.push(GetAttributesPriceFromItem(e) ? GetAttributesPriceFromItem(e).getFormattedText() : '');
        })
        let time = new Date(Auctions.lastUpdated);
        AttributesPriceText.push('§a数据更新时间 §5' + time.toLocaleTimeString());
    }, 300); } catch (error) { }
})
register("guiClosed", () => { AttributesPriceText = []; })
register("renderOverlay", () => {
    if(guiMover.gui.isOpen() && settings.AttributesPrice) DrawString("&r&bmana pool 4 &6在&bchestplate&6上的价格是 &a4M\n&bmana regeneration 1 &6在&bchestplate&6上的价格是 &a5.4M\n&bmana pool &6和&b mana regeneration &6在&bAURORA CHESTPLATE&6上的价格是 &a270M\n&r&a数据更新时间 &5上午01时39分18秒",guiMover.settings.attPrice.x,guiMover.settings.attPrice.y,guiMover.settings.attPrice.s,true);
})
register("guiRender", (mx,my,gui) => {
    if(guiMover.gui.isOpen() || !settings.AttributesPrice || AttributesPriceText.length == 0) return;
    DrawString(AttributesPriceText.join('\n'),guiMover.settings.attPrice.x,guiMover.settings.attPrice.y,guiMover.settings.attPrice.s,true);
})

//指令手动查
function ShowAttributesPriceOnChat(a1,a2) {
    let items = GetAttributesPrice(a1,a2);
    if(!items) return;
    new Message(("§6§l[BZA] §a以下是 §b" + replaceAttributeName(a1) + (parseInt(a2) && parseInt(a2) < 11 ? ' ' : " §a和§b ") + replaceAttributeName(a2) + " §a在ah上的价格\n") , new TextComponent("§a数据更新时间 §5" + new Date(Auctions.lastUpdated).toLocaleString()).setClick("run_command","/babyzombieaddons ap update").setHover("show_text","§5点击重新获取Auctions数据"), '\n').chat();
    for (let key in items) {
        if(items[key][0]) {
            items[key].forEach(e=>{
                ChatLib.chat(new TextComponent(e.name + '   §a' + (parseInt(e.price / 10000) / 100) + 'M')
                .setClick("run_command","/viewauction " + e.ahid).setHover("show_text",e.name + '\n' + e.lore))
            })
            ChatLib.chat('');
        }
    }
}


const AttName = {as:"attack_speed",bf:"blazing_fortune",br:"breeze",co:"combo:",de:"deadeye",do:"dominance",dh:"double_hook",el:"elite",ex:"experience",fo:"fortitude",fm:"fisherman",fe:"fishing_experience",fs:"fishing_speed",ig:"ignition",in:"infection",ls:"life_recovery",lr:"life_regeneration",ll:"lifeline",mf:"magic_find",mp:"mana_pool",mr:"mana_regeneration",ms:"mana_steal",mt:"midas_touch",sp:"speed",th:"trophy_hunter",ve:"veteran",vitality:"mending",vi:"mending",wa:"warrior"}
export function GetAttributesPriceAndItem(a1,a2) {
    let att1 = a1.toLowerCase(); let att2 = a2.toLowerCase();
    if(AttName[att1]) att1 = AttName[att1];
    if(AttName[att2]) att2 = AttName[att2];
    if( !Auctions.loading && (!Auctions.lastUpdated || (settings.AuctionsRequest && Date.now() - Auctions.lastUpdated > settings.AuctionsRequestTime * 60 * 1000) ) ) {
        ChatLib.chat("§6§l[BZA] §eAH数据过旧或不存在,正在重新获取");
        Auctions.getAllAuctionsFromHypixelAPI(true).then( e => { ShowAttributesPriceOnChat(att1,att2) } )
    } else ShowAttributesPriceOnChat(att1,att2);
}

export function GetAttributesPriceFromHeldItem() {
    let item = Player.getHeldItem();
    if(!item) {ChatLib.chat("§6§l[BZA] §c您没有手持一个物品");return;}
    if(!GetAttributesFrom(item)) {ChatLib.chat("§6§l[BZA] §c手中物品没有属性词条");return;}
    if( !Auctions.loading && (!Auctions.lastUpdated || (settings.AuctionsRequest && Date.now() - Auctions.lastUpdated > settings.AuctionsRequestTime * 60 * 1000) ) ) {
        ChatLib.chat("§6§l[BZA] §eAH数据过旧或不存在,正在重新获取");
        Auctions.getAllAuctionsFromHypixelAPI(true).then( e => { 
            GetAttributesPriceFromItem(item).chat();
            new TextComponent('§a数据更新时间 §5' + new Date(Auctions.lastUpdated).toLocaleString()).setClick("run_command","/babyzombieaddons ap update").setHover("show_text","§5点击重新获取Auctions数据").chat();
        } )
    } else {
        GetAttributesPriceFromItem(item).chat();
        new TextComponent('§a数据更新时间 §5' + new Date(Auctions.lastUpdated).toLocaleString()).setClick("run_command","/babyzombieaddons ap update").setHover("show_text","§5点击重新获取Auctions数据").chat();
    }
}

//在其他地方指着物品时显示词条价格
let mouseSlot = -1;
register("guiRender", (mx,my,gui) => {
    if(!settings.AttributesPrice || !Auctions.lastUpdated || !location.inSkyblock) return;
    try {
        if(location.inKuudra && Player.getContainer() != undefined && Player.getContainer().getName().removeFormatting() == "Paid Chest") return;
        const slot = gui.getSlotUnderMouse();
        if(!slot) {
            AttributesPriceText = [];
            return;
        }
        if(slot.field_75222_d != mouseSlot) {
            mouseSlot = slot.field_75222_d;
            AttributesPriceText = [];
        } else return;
        const item = getItemFromGui(gui);
        if(!item || !GetAttributesFrom(item)) return;
        const message = GetAttributesPriceFromItem(item);
        if(message === null) return;
        AttributesPriceText.push(message.getFormattedText().replace(/\r\n/g,'\n') + '§a以上价格数据更新时间 §5' + new Date(Auctions.lastUpdated).toLocaleString());
    } catch (error) {}
})